﻿using Microsoft.OpenApi.Any;
using Microsoft.OpenApi.Models;
using Swashbuckle.AspNetCore.SwaggerGen;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace WenDangOne.Lib
{
    public class AddTokenHeaderParameter: IOperationFilter
    {
        public void Apply(OpenApiOperation operation, OperationFilterContext context)
        {
            if (operation.Parameters == null)
                operation.Parameters = new List<OpenApiParameter>();
            var attrs = context.ApiDescription.GetType().GetCustomAttributes(typeof(UserTokenVerificationAttribute), false);
            foreach (var attr in attrs)
            {
                // 如果 Attribute 是我们自定义的验证过滤器
                if (attr.GetType() == typeof(UserTokenVerificationAttribute))
                {
                    operation.Parameters.Add(new OpenApiParameter
                    {
                        Name = "X-Token",
                        In = ParameterLocation.Header,
                        Description = "请求Token",
                        Required = true,
                        Schema = new OpenApiSchema
                        {
                            Type = "string",
                            Default = new OpenApiString("Bearer {access token}"),
                        }
                    });
                }
            }
        }
    }
}
